<template>
    <div class="role-config">
        <div class="page-header">
            <h2>角色配置</h2>
            <div>
                <el-button type="primary" @click="openAddDialog">添加角色</el-button>
                <el-button class="refreshRoleData" :icon="Refresh" @click="refreshRoles" circle />
            </div>
        </div>

        <!-- 角色列表 -->
        <el-table :data="roles" style="width: 100%" border>
            <el-table-column label="角色名" prop="name"></el-table-column>
            <el-table-column label="描述" prop="description"></el-table-column>
            <el-table-column label="启用状态" prop="enable">

                <template #default="{ row }">
                    <el-tag :type="row.enable ? 'success' : 'danger'">
                        {{ row.enable ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime"></el-table-column>

            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button @click="openEditDialog(row)" type="text" size="small">编辑</el-button>
                    <el-button @click="deleteRole(row.id)" type="text" size="small" style="color: red;">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加/编辑角色弹窗 -->
        <el-dialog v-model="dialogVisible" title="角色配置" width="400px" :before-close="closeDialog">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="dialog-form">

                <!-- 角色名 -->
                <el-form-item label="角色名" prop="name">
                    <el-input v-model="form.name" placeholder="请输入角色名" />
                </el-form-item>

                <!-- 描述 -->
                <el-form-item label="描述" prop="description">
                    <el-input v-model="form.description" placeholder="请输入描述" />
                </el-form-item>
            </el-form>

            <!-- 启用状态 -->
            <el-form-item label="启用状态">
                <el-switch v-model="form.enable" active-text="启用" inactive-text="禁用" />
            </el-form-item>

            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialog" size="medium">取消</el-button>
                <el-button type="primary" @click="saveRole" size="medium">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { onMounted, inject, ref, reactive } from 'vue';
const axios = inject('$axios'); // 从全局属性注入
import { Refresh } from '@element-plus/icons-vue'

const dialogVisible = ref(false);
const form = ref({
    id: 0,
    name: '',
    enable: true,
    description: '',
    createTime: ''
});
const isEdit = ref(false);

const roles = ref([]);
const formRef = ref(null);

const rules = ref({
    name: [
        { required: true, message: '角色名不能为空', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '描述不能为空', trigger: 'blur' }
    ]
});

// 打开添加角色对话框
const openAddDialog = () => {
    form.value = {
        id: 0,
        name: '',
        description: '',
        createTime: '',
        enable: true
    };
    isEdit.value = false;
    dialogVisible.value = true;
};

// 打开编辑角色对话框
const openEditDialog = (row) => {
    form.value = { ...row };
    dialogVisible.value = true;
    isEdit.value = true;
};

// 关闭对话框
const closeDialog = () => {
    if (formRef.value) {
        formRef.value.resetFields(); // 重置表单
    }
    dialogVisible.value = false;
};

// 保存角色
const saveRole = async () => {
    const valid = await new Promise((resolve, reject) => {
        formRef.value.validate((valid) => {
            if (!valid) {
                ElMessage.error('请完善必填项');
                reject(new Error('请完善必填项'));
            } else {
                resolve(valid);
            }
        });
    });

    if (!valid) return;

    const dataParam = {
        id: form.value.id ?? 0,
        name: form.value.name,
        description: form.value.description,
        enable:form.value.enable
    };

    let result;

    if (dataParam.id > 0) {
        // 编辑角色
        result = await axios.post('/Role/EditRoleAsync', dataParam);
    } else {
        // 添加角色
        result = await axios.post('/Role/AddRoleAsync', dataParam);
    }

    if (result.statusCode === 200 && result.success === true) {
        ElMessage.success(result.message);
        getRoles();
    } else {
        ElMessage.error(result.message);
    }

    closeDialog();
};

// 删除角色
const deleteRole = async (id) => {
    const result = await axios.get('/Role/DeleteRoleAsync?id=' + id);
    if (result.statusCode === 200 && result.success === true) {
        ElMessage.success('角色删除成功');
        getRoles();
    } else {
        ElMessage.error(result.message);
    }
};

// 获取角色数据
const refreshRoles = async () => {
    getRoles();
    ElMessage.success('刷新成功');
};

const getRoles = async () => {
    const result = await axios.get('/Role/QueryRoleAsync');
    if (result.statusCode === 200 && result.success === true) {
        roles.value = result.response;
    } else {
        ElMessage.error('获取角色列表失败');
    }
}

onMounted(() => {
    getRoles();
});
</script>

<style scoped>
.page-header {
    display: flex;
    justify-content: space-between;
}

.refreshRoleData {
    margin-left: 10px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    padding: 10px 20px;
}

.dialog-footer .el-button {
    width: 80px;
    margin-left: 20px;
}
</style>
